package com.xcyy.clbzbh.controller;

import com.xcyy.clbzbh.VO.ResultVO;
import com.xcyy.clbzbh.VO.UserVO;
import com.xcyy.clbzbh.common.ResultVOUtil;
import com.xcyy.clbzbh.entity.Role;
import com.xcyy.clbzbh.entity.TokenInfo;
import com.xcyy.clbzbh.entity.User;
import com.xcyy.clbzbh.entity.UserRole;
import com.xcyy.clbzbh.service.RoleService;
import com.xcyy.clbzbh.service.TokenService;
import com.xcyy.clbzbh.service.UserRoleService;
import com.xcyy.clbzbh.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@RestController
public class UserController {
    
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private TokenService tokenService;


    @PostMapping("/login")
    public ResultVO login(String username,String password, HttpServletResponse response){

        User result=userService.findByUsernameAndPassword(username, password);
        if (result!=null){
            //获取token
            String tokenStr=null;
            TokenInfo tokenInfo=tokenService.findByUsername(result.getUsername());
            if (tokenInfo==null){
                tokenInfo=new TokenInfo();
                tokenStr=createNewToken(result.getUsername());
                tokenInfo.setUsername(result.getUsername());
                tokenInfo.setBuildTime(String.valueOf(System.currentTimeMillis()));
                tokenInfo.setToken(tokenStr.getBytes());
                tokenService.save(tokenInfo);
            }else {
                long dbBuildTime=Long.valueOf(tokenInfo.getBuildTime());
                long currentTime=System.currentTimeMillis();
                long second= currentTime-dbBuildTime;
                if(second>0&&second<7000000){
                    tokenStr=new String(tokenInfo.getToken());
                }else {
                    tokenStr=createNewToken(result.getUsername());
                    tokenInfo.setToken(tokenStr.getBytes());
                    tokenInfo.setBuildTime(String.valueOf(System.currentTimeMillis()));
                    tokenService.save(tokenInfo);
                }
            }
           /* Cookie cookieToken=new Cookie("BZ-Token",tokenStr);
            cookieToken.setPath("/");
            cookieToken.setMaxAge(3600);
            response.addCookie(cookieToken);
            Cookie cookieUserId=new Cookie("username",result.getUsername());
            cookieUserId.setPath("/");
            cookieUserId.setMaxAge(3600);
            response.addCookie(cookieUserId);*/
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(result,userVO);
            userVO.setBZToken(tokenStr);
            return ResultVOUtil.success(userVO);
        }
        return ResultVOUtil.error(403,"登录失败");
    }

    @PostMapping("/loginapp")
    public ResultVO loginAPP(String username,String password){
        User user=userService.findByUsernameAndPassword(username, password);
        //查询角色
        UserRole userRole = userRoleService.findByUserId(user.getId());
        if (user!=null){
            if("1".equals(userRole.getRoleId())){
                //获取token
                String tokenStr=null;
                TokenInfo tokenInfo=tokenService.findByUsername(user.getUsername());
                if (tokenInfo==null){
                    tokenInfo=new TokenInfo();
                    tokenStr=createNewToken(user.getUsername());
                    tokenInfo.setUsername(user.getUsername());
                    tokenInfo.setBuildTime(String.valueOf(System.currentTimeMillis()));
                    tokenInfo.setToken(tokenStr.getBytes());
                    tokenService.save(tokenInfo);
                }else {
                    long dbBuildTime=Long.valueOf(tokenInfo.getBuildTime());
                    long currentTime=System.currentTimeMillis();
                    long second= currentTime-dbBuildTime;
                    if(second>0&&second<7000000){
                        tokenStr=new String(tokenInfo.getToken());
                    }else {
                        tokenStr=createNewToken(user.getUsername());
                        tokenInfo.setToken(tokenStr.getBytes());
                        tokenInfo.setBuildTime(String.valueOf(System.currentTimeMillis()));
                        tokenService.save(tokenInfo);
                    }
                }

                return   ResultVOUtil.success(tokenStr);
            }else {
                return ResultVOUtil.error(501,"暂无权限");
            }
        }else {
            return ResultVOUtil.error(403,"登录失败");
        }
    }

    @PostMapping("/updateuser")
    public ResultVO updateUser(User user){
        User result=userService.save(user);
        return ResultVOUtil.success(result);
    }

    @PostMapping("/adduser")
    @Transactional
    public ResultVO addUser(User user, String roleId){

        User userResult=userService.addUser(user);
        Role roleResult=roleService.findById(roleId);
        UserRole userRole=new UserRole();
        userRole.setUserId(userResult.getId());
        userRole.setRoleId(roleResult.getId());
        userRoleService.add(userRole);

       return ResultVOUtil.success( userResult);

    }

    private String createNewToken(String username) {
        Date now=new Date(System.currentTimeMillis());
        Date expiration=new Date(now.getTime()+72000000);
        return Jwts
                .builder()
                .setSubject(username)
                .setIssuedAt(now)
                .setIssuer("湖南省测量标志保护")
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256,"Alec")
                .compact();
    }
}
